package io2.nio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;

public class NioServer {
    static final byte[] RS = "HTTP/1.1 200 OK\r\nContent-length:13\r\n\r\nHello, World!\r\n".getBytes();
    public static void main(String[] args) throws IOException {
        ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
        serverSocketChannel.configureBlocking(false);
        serverSocketChannel.bind(new InetSocketAddress(8080));
        System.out.println("服务启动，监听8080端口");
        while(true) {
            SocketChannel socketChannel = serverSocketChannel.accept();
            if(socketChannel != null) {
                System.out.println("新建连接：" + socketChannel.getRemoteAddress());
                socketChannel.configureBlocking(false);
                ByteBuffer buffer = ByteBuffer.allocate(1024);
                while(true) {
                    if(socketChannel.read(buffer) > 0) {
                        buffer.flip();
                        byte[] bytes = new byte[buffer.remaining()];
                        buffer.get(bytes);
                        System.out.println("收到数据：" + new String(bytes));
                        buffer.clear();
                        break;
                    }
                }
                System.out.println("数据接收完毕， 来源于：" + socketChannel.getRemoteAddress());
                socketChannel.write(ByteBuffer.wrap(RS));
                System.out.println("数据发送完毕");
                socketChannel.close();
            }
        }
    }
}
